import axios from 'axios'

import {
  Toast
} from 'vant';
import store from "../../store";
import router from '../../router/index.js'


// 显示错误
function errorLog(msg) {
  if (msg) {
    // 显示提示
    Toast(msg);
  }
  return
}

axios.defaults.timeout = 60000
axios.defaults.baseURL = process.env.VUE_APP_URL




// 请求拦截器
axios.interceptors.request.use(
  config => {
    config.headers['content-type'] = 'application/json'
    return config
  },
  error => {
    // 发送失败
    console.log('接口发送失败:', error)
    return Promise.reject(error)
  }
)
// 响应拦截器
axios.interceptors.response.use(
  response => {
    // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data

    const {
      code
    } = dataAxios

    // 根据 code 进行判断,此处根据后端接口给的值灵活变动条件
    switch (code) {
      case 1:
        return dataAxios
      case 0:
        errorLog(dataAxios.msg);
        return Promise.reject(dataAxios)
      case -1:
        errorLog(dataAxios.msg);
        // Toast.clear()
        localStorage.clear()
        router.push({
          path: "/login"
        })
        return Promise.reject(dataAxios)
      default:
        errorLog(dataAxios.msg)
        return Promise.reject(dataAxios)
    }
  },
  error => {
    errorLog(error.msg)
    return Promise.reject(error)
  }
)

export function post(url, params) {
  // console.log(params, "params")
  params.loading ? store.state.showOverlay = true : store.state.showOverlay = false;
  let resParams;
  if (localStorage.getItem("token")) {
    params.token = localStorage.getItem("token");
  }
  resParams = {
    method: 'post',
    url: url,
    data: params,
    cus_params: params,
  }


  return new Promise((resolve, reject) => {
    axios.post(url, resParams.data).then(res => {
        if (res) {
          store.state.showOverlay = false;
          resolve(res);
        } else {
          store.state.showOverlay = false;
          resolve(res);
        }
      })
      .catch(err => {
        store.state.showOverlay = false;
        reject(err)
      })
  });
}

// 二进制不需要加密
export function upload(url, params) {
  let resParams;
  resParams = {
    method: "post",
    url: url,
    data: params
  }
  return new Promise((resolve, reject) => {
    axios.post(url, resParams.data)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err)
      })
  });
}